package com.antrain.ssm.controller;

import java.util.Map;

import javax.annotation.Resource;

import com.antrain.ssm.pojo.User;
import com.antrain.ssm.service.UserService;
import com.antrain.ssm.util.PageResult;
import com.antrain.ssm.util.PageUtil;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 初始显示数据
     * @param params 包含分页参考 （page 默认1 limit 默认3）
     * @param model 封装处理的结果
     * @return 视图名
     */
    @GetMapping({"/","/index","/list"})
    public String index(@RequestParam Map<String, Object> params,Model model){
        PageResult pageResult = userService.queryUsers(new PageUtil(params));
        model.addAttribute("data", pageResult);
        if(params.get("name")!=null){
            model.addAttribute("name", params.get("name"));
        }else{
            model.addAttribute("name", "");
        }
        return "index";
    }

    @ResponseBody
    @GetMapping("/test")
    public PageResult test(@RequestParam(required = false) Map<String, Object> params){
        PageResult pageResult = userService.queryUsers(new PageUtil(params));
        System.out.println(pageResult.toString());
        return pageResult;
    }

    @RequestMapping("/del")
    public String del(Integer id) {
        userService.del(id);
        return "redirect: /ssmdemo/list";
    }

    @ResponseBody
    @RequestMapping("/get")
    public User get(Integer id) {
        return userService.queryById(id);
    }

    @PostMapping("/add")
    public String add(User user) {
        userService.insert(user);
        return "redirect: /ssmdemo/list";
    }

    @PostMapping("/update")
    public String update(User user) {
        userService.update(user);
        return "redirect: /ssmdemo/list";
    }
}